package system.service.sys.impl;

import framework.exceptions.BusinessException;
import framework.utils.RequestUtil;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import system.entity.SysPermission;
import system.mapper.SysPermissionMapper;
import system.service.sys.SysConfigService;
import system.service.sys.SysPermissionService;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysPermissionServiceImpl implements SysPermissionService {
    @Autowired
    @Getter
    private SysPermissionMapper mapper;
    @Autowired
    private SysConfigService configService;

    @Override
    public Integer add(SysPermission param) {
        int rows = SysPermissionService.super.add(param);
        //
        configService.updateConfigVersion();
        return rows;
    }

    @Transactional
    public Integer update(SysPermission param, String oldId) {
        if ("SysPermission.Read".equals(oldId) || "SysPermission.Create".equals(oldId)
                || "SysPermission.Update".equals(oldId)
                || "SysPermission.Delete".equals(oldId)) {
            throw new BusinessException(RequestUtil.getMessageDefault("permission.operation.deny", "not allowed change this permission"));
        }
        //
        int rows = 0;
        rows += mapper.deleteById(oldId);
        rows += mapper.add(param);
        //
        configService.updateConfigVersion();
        return rows;
    }

    @Override
    @Transactional
    public Integer deleteById(String id) {
        if ("SysPermission.Read".equals(id) || "SysPermission.Create".equals(id)
                || "SysPermission.Update".equals(id)
                || "SysPermission.Delete".equals(id)) {
            throw new BusinessException(RequestUtil.getMessageDefault("permission.operation.deny", "not allowed change this permission"));
        }
        //
        int deleted = 0;
        SysPermission permission = new SysPermission();
        permission.setPid(id);
        List<SysPermission> list = this.load(permission);
        if (list.size() > 0) {
            List<String> idList = list.stream().map(p -> p.getId()).collect(Collectors.toList());
            deleted += this.deleteByIds(idList);
        }
        deleted += SysPermissionService.super.deleteById(id);
        //
        configService.updateConfigVersion();
        return deleted;
    }

}